package com.jessechanrui.template.shardingsphere.demo.service;

import com.jessechanrui.template.shardingsphere.demo.assembler.DemoAssembler;
import com.jessechanrui.template.shardingsphere.demo.dto.DemoDTO;
import com.jessechanrui.template.skeleton.domain.demo.entity.Demo;
import com.jessechanrui.template.skeleton.domain.demo.support.repository.DemoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 示例应用服务
 * @author chenrui
 * @date 2024/1/30
 */
@Service
public class DemoAppService {

    @Autowired
    private DemoAssembler demoAssembler;

    @Autowired
    private DemoRepository demoRepository;

    public DemoDTO saveData(DemoDTO demoDTO){
        Demo demo = demoAssembler.toEntity(demoDTO);
        demo = demoRepository.save(demo);
        demoDTO = demoAssembler.toDTO(demo);
        return demoDTO;
    }

    @Cacheable(cacheNames = "demo_getById", key = "#id")
    public DemoDTO getById(Integer id){
        Demo demo = demoRepository.getById(id);
        return demoAssembler.toDTO(demo);
    }

    /**
     * 使用了缓存注解后，后面在数据库中添加记录，调用该方法时从已有缓存中获取，读取不到新加的记录
     * @return
     */
    @Cacheable(cacheNames = "demo_findAll")
    public List<DemoDTO> findAll(){
        List<Demo> all = demoRepository.getAll();
        return demoAssembler.toDTOList(all);
    }
}
